package com.ms.pda.utils.frid;

import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ms.pda.R;
import com.rscja.deviceapi.entity.UHFTAGInfo;
import com.rscja.deviceapi.interfaces.ConnectionStatus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Package: com.ms.pda.utils.frid
 * @Description: java类作用描述
 * @Author: ldy
 * @CreateDate: 2023/11/1 15:24
 */
public class UHFReadTagManager {
    private String TAG = "UHFReadTagManager";

    private ConnectStatus mConnectStatus = new ConnectStatus();
    int maxRunTime = 99999999;
    //--------------------------------------获取 解析数据-------------------------------------------------
    final int FLAG_START = 0;//开始
    final int FLAG_STOP = 1;//停止
    final int FLAG_UPDATE_TIME = 2; // 更新时间
    final int FLAG_UHFINFO = 3;
    final int FLAG_UHFINFO_LIST = 5;
    final int FLAG_SUCCESS = 10;//成功
    final int FLAG_FAIL = 11;//失败
    private long mStrTime;
    private CWFridManager mContext;

    public UHFReadTagManager(CWFridManager mContext) {
        this.mContext = mContext;
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FLAG_STOP:
                    if (msg.arg1 == FLAG_SUCCESS) {
                        //停止成功
//                        InventoryLoop.setEnabled(true);
                    } else {
                        //停止失败
//                        Utils.playSound(2);
                        ToastUtils.showShort(R.string.uhf_msg_inventory_stop_fail);
                    }
                    break;
                case FLAG_UHFINFO_LIST:
                    List<UHFTAGInfo> list = (List<UHFTAGInfo>) msg.obj;
                    addEPCToList(list);
                    break;
                case FLAG_START:
                    if (msg.arg1 == FLAG_SUCCESS) {
                        //开始读取标签成功
//                        InventoryLoop.setEnabled(false);
                    } else {
                        //开始读取标签失败
//                        Utils.playSound(2);
                    }
                    break;
                case FLAG_UPDATE_TIME:
                    float useTime = (System.currentTimeMillis() - mStrTime) / 1000.0F;
//                    tv_time.setText(NumberTool.getPointDouble(1, useTime) + "s");
                    break;
                case FLAG_UHFINFO:
                    UHFTAGInfo info = (UHFTAGInfo) msg.obj;
                    List list1 = new ArrayList<UHFTAGInfo>();
                    list1.add(info);
                    addEPCToList(list1);
                    break;
            }
        }
    };

    private void addEPCToList(List<UHFTAGInfo> list) {
        Log.i(TAG, "addEPCToList：" + GsonUtils.toJson(list));
    }

    public void init() {
        init();
        mContext.setSelectEPC(null);
    }


    public void onPause() {
        stop();
    }

    public void onDestroy() {
        mContext.removeConnectStatusNotice(mConnectStatus);
    }

    public void onResume() {
        if (mContext.getUhf().getConnectStatus() == ConnectionStatus.CONNECTED) {
//            InventoryLoop.setEnabled(true);
        } else {
//            InventoryLoop.setEnabled(false);
        }
    }


    class ConnectStatus implements CWFridManager.IConnectStatus {
        @Override
        public void getStatus(ConnectionStatus connectionStatus) {
            if (connectionStatus == ConnectionStatus.CONNECTED) {
                if (!mContext.isScanning()) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    InventoryLoop.setEnabled(true);
                }
            } else if (connectionStatus == ConnectionStatus.DISCONNECTED) {
                stop();
//                InventoryLoop.setEnabled(false);
            }
        }
    }

    private void stopInventory() {
        //Log.i(TAG, "stopInventory() 2");
        boolean result = mContext.getUhf().stopInventory();
        ConnectionStatus connectionStatus = mContext.getUhf().getConnectStatus();
        Message msg = handler.obtainMessage(FLAG_STOP);
        if (!result || connectionStatus == ConnectionStatus.DISCONNECTED) {
            msg.arg1 = FLAG_FAIL;
        } else {
            msg.arg1 = FLAG_SUCCESS;
        }
        handler.sendMessage(msg);
    }

    /**
     * 停止识别
     */
    private void stop() {
        cancelInventoryTask();
        mContext.setScanning(false);
    }

    public void startThread() {
        maxRunTime = 9999999 * 1000;

        mContext.setScanning(true);
//        cbFilter.setChecked(true);
        new TagThread().start();
    }


    class TagThread extends Thread {
        public void run() {
            Message msg = handler.obtainMessage(FLAG_START);
            Log.i(TAG, "startInventoryTag() 1");
            if (mContext.getUhf().startInventoryTag()) {
                mStrTime = System.currentTimeMillis();
                msg.arg1 = FLAG_SUCCESS;
            } else {
                msg.arg1 = FLAG_FAIL;
                mContext.setScanning(false);
            }
            handler.sendMessage(msg);
            long startTime = System.currentTimeMillis();
            while (mContext.isScanning()) {
                List<UHFTAGInfo> list = getUHFInfo();
                if (list == null || list.size() == 0) {
                    SystemClock.sleep(1);
                } else {
//                    Utils.playSound(1);
                    handler.sendMessage(handler.obtainMessage(FLAG_UHFINFO_LIST, list));
                }
                if (System.currentTimeMillis() - startTime > 10) {
                    startTime = System.currentTimeMillis();
                    handler.sendEmptyMessage(FLAG_UPDATE_TIME);
                }
                //-------------------------
                if ((System.currentTimeMillis() - mStrTime) >= maxRunTime) {
                    mContext.setScanning(false);
                    break;
                }
                //--------------------------------
            }
            stopInventory();
        }
    }

    private synchronized List<UHFTAGInfo> getUHFInfo() {
        List<UHFTAGInfo> list = null;
        if (mContext.isSupportRssi()) {
            //旧主板才需要调用readTagFromBufferList_EpcTidUser 输出 RSSI
            list = mContext.getUhf().readTagFromBufferList_EpcTidUser();
        } else {
            //读写器主板版本 2.20-2.29 readTagFromBufferList 函数支持输出Rssi，无需调用readTagFromBufferList_EpcTidUser
            list = mContext.getUhf().readTagFromBufferList();
        }
        return list;
    }


    private Timer mTimer = new Timer();
    private TimerTask mInventoryPerMinuteTask;
    private long period = 6 * 1000; // 每隔多少ms

    private void inventoryPerMinute() {
        cancelInventoryTask();

//        InventoryLoop.setEnabled(false);

        mContext.setScanning(true);
        mInventoryPerMinuteTask = new TimerTask() {
            @Override
            public void run() {
                inventory();
            }
        };
        mTimer.schedule(mInventoryPerMinuteTask, 0, period);
    }

    private void cancelInventoryTask() {
        if (mInventoryPerMinuteTask != null) {
            mInventoryPerMinuteTask.cancel();
            mInventoryPerMinuteTask = null;
        }
    }

    private void inventory() {
        mStrTime = System.currentTimeMillis();
        UHFTAGInfo info = mContext.getUhf().inventorySingleTag();
        if (info != null) {
            Message msg = handler.obtainMessage(FLAG_UHFINFO);
            msg.obj = info;
            handler.sendMessage(msg);
        }
        handler.sendEmptyMessage(FLAG_UPDATE_TIME);
    }
}